<?php

/**
 * Implements hook_field_formatter_info();
 */
function image_lazy_field_formatter_info() {
  $formatters = array(
      'image_lazy' => array(
          'label' => t('Image lazy load'),
          'field types' => array('image'),
          'settings' => array(
              'image_style' => '',
              'image_link' => '',
              'lazy_effect' => '',
              'lazy_event' => ''
          ),
      ),
  );
  return $formatters;
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function image_lazy_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $element = image_field_formatter_settings_form($field, $instance, $view_mode, $form, $form_state);
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $effects = array(
      'show' => 'Show (default)',
      'fadeIn' => 'Fade in',
      'slideDown' => 'Slide down'
  );
  $element['lazy_effect'] = array(
      '#title' => t('Lazy effect'),
      '#type' => 'select',
      '#default_value' => $settings['lazy_effect'],
      '#options' => $effects,
  );
  $events = array(
      'scroll' => 'Scroll (default)',
      'mouseover' => 'Mouse over',
      'click' => 'Click'
  );
  $element['lazy_event'] = array(
      '#title' => t('Lazy event'),
      '#type' => 'select',
      '#default_value' => $settings['lazy_event'],
      '#options' => $events,
  );
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function image_lazy_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $summary = array();

  $image_styles = image_style_options(FALSE);
  // Unset possible 'No defined styles' option.
  unset($image_styles['']);
  // Styles could be lost because of enabled/disabled modules that defines
  // their styles in code.
  if (isset($image_styles[$settings['image_style']])) {
    $summary[] = t('Image style: @style', array('@style' => $image_styles[$settings['image_style']]));
  } else {
    $summary[] = t('Original image');
  }

  $link_types = array(
      'content' => t('Linked to content'),
      'file' => t('Linked to file'),
  );
  // Display this setting only if image is linked.
  if (isset($link_types[$settings['image_link']])) {
    $summary[] = $link_types[$settings['image_link']];
  }
  $effects = array(
      'show' => 'Show (default)',
      'fadeIn' => 'Fade in',
      'slideDown' => 'Slide down'
  );

  if (!empty($settings['lazy_effect'])) {
    $summary[] = 'Lazy effect: ' . $effects[$settings['lazy_effect']];
  }
  $events = array(
      'scroll' => 'Scroll (default)',
      'mouseover' => 'Mouse over',
      'click' => 'Click'
  );
  if (!empty($settings['lazy_event'])) {
    $summary[] = 'Lazy event: ' . $events[$settings['lazy_event']];
  }
  return implode('<br />', $summary);
}

/**
 * Implements hook_field_formatter_view().
 */
function image_lazy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  static $aggr_settings = array();
  $identity = uniqid();
  $added = true;
  foreach ($aggr_settings as $exist_identity => $settings) {
    if ($settings == $display['settings']) {
      $added = false;
      $identity = $exist_identity;
      break;
    }
  }
  if ($added) {
    $aggr_settings[$identity] = $display['settings'];
  }
  if ($aggr_settings)
    drupal_add_js(array('image_lazy' => $aggr_settings), array('type' => 'setting'));

  $element = array();
//  drupal_add_js(array(
//      ''
//  ), array('type' => 'settings'));
  // Check if the formatter involves a link.
  if ($display['settings']['image_link'] == 'content') {
    $uri = entity_uri($entity_type, $entity);
  } elseif ($display['settings']['image_link'] == 'file') {
    $link_file = TRUE;
  }

  foreach ($items as $delta => $item) {
    if (isset($link_file)) {
      $uri = array(
          'path' => file_create_url($item['uri']),
          'options' => array(),
      );
    }
    $element[$delta] = array(
        '#theme' => 'image_lazy_formatter',
        '#identity' => $identity,
        '#item' => $item,
        '#image_style' => $display['settings']['image_style'],
        '#path' => isset($uri) ? $uri : '',
    );
  }

  return $element;
}

/**
 * Returns HTML for an image field formatter.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
 *   - path: An array containing the link 'path' and link 'options'.
 *
 * @ingroup themeable
 */
function theme_image_lazy_formatter($variables) {
  $item = $variables['item'];
  $image = array(
      'path' => $item['uri'],
      'alt' => $item['alt']
  );
  $image['attributes']['class'][] = $variables['identity'];
  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  // Do not output an empty 'title' attribute.
  if (drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style_lazy', $image);
  } else {
    $output = theme('image_lazy', $image);
  }

  if (!empty($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = $variables['path']['options'];
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
  }

  return $output;
}
